<template>
  <view class="container">
    <view class="list-container">
      <view 
        class="list-item" 
        v-for="(item, index) in departmentList" 
        :key="index"
        @tap="goToDepartmentDetail(item)"
      >
        <image :src="item.imgUrl || '/static/images/default-department.png'" mode="aspectFill" class="item-image"></image>
        <view class="item-info">
          <text class="item-name">{{ item.name }}</text>
          <text class="item-detail">{{ item.hospitalName }}</text>
          <text class="item-snapshot">{{ item.snapshot }}</text>
          <text class="item-count">{{ item.hospitals?.length || 0 }}家医院</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { selectDepartmentAll } from '@/api/department'

export default {
  data() {
    return {
      departmentList: [],
      searchHistory: []
    }
  },
  onLoad() {
    this.loadSearchHistory()
    this.loadDepartmentList()
  },
  methods: {
    loadSearchHistory() {
      this.searchHistory = uni.getStorageSync('searchHistory') || []
    },
    async loadDepartmentList() {
      try {
        const res = await selectDepartmentAll()
        if (res.code === 200 && Array.isArray(res.data)) {
          // 合并相同名称的科室
          const mergedDepartments = this.mergeDepartments(res.data)
          
          if (this.searchHistory.length > 0) {
            // 如果有搜索历史，优先显示匹配的结果
            const filtered = mergedDepartments.filter(item => {
              return this.searchHistory.some(keyword => {
                const lowerCaseKeyword = keyword.toLowerCase()
                return ['name', 'description', 'hospitalName'].some(field => {
                  const value = item[field]
                  return value && String(value).toLowerCase().includes(lowerCaseKeyword)
                })
              })
            })
            this.departmentList = filtered.length > 0 ? filtered : mergedDepartments
          } else {
            this.departmentList = mergedDepartments
          }
        }
      } catch (error) {
        console.error('获取科室列表失败:', error)
        uni.showToast({
          title: '获取科室列表失败',
          icon: 'none'
        })
      }
    },
    mergeDepartments(departments) {
      const mergedMap = new Map()
      
      departments.forEach(dept => {
        if (!mergedMap.has(dept.name)) {
          mergedMap.set(dept.name, {
            id: dept.id,
            name: dept.name,
            diseaseType: dept.diseaseType,
            snapshot: dept.snapshot,
            hospitals: [{
              hospitalName: dept.hospitalName,
              address: dept.address,
              id: dept.hospitalId
            }]
          })
        } else {
          const existing = mergedMap.get(dept.name)
          existing.hospitals.push({
            hospitalName: dept.hospitalName,
            address: dept.address,
            id: dept.hospitalId
          })
        }
      })
      
      return Array.from(mergedMap.values())
    },
    goToDepartmentDetail(item) {
      if (item.id) {
        uni.navigateTo({
          url: `/pages/department/detail?id=${item.id}`,
          success: (res) => {
            res.eventChannel.emit('departmentData', item)
          }
        })
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #F5F6FA;
  min-height: 100vh;
}

.list-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.list-item {
  display: flex;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  padding: 24rpx;
  align-items: center;
}

/* 浅色背景 */
/* .bg-department-light { background-color: #f6ffed; } */

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.item-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
}

.item-detail {
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 4rpx;
}

.item-snapshot {
  font-size: 26rpx;
  color: #777777;
  margin-bottom: 6rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}

.item-count {
  font-size: 26rpx;
  color: #999999;
  margin-top: 6rpx;
}

/* .item-desc {
  font-size: 24rpx;
  color: #999999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
} */
</style> 